package com.wedo.book.interceptor;

import com.wedo.auth.pojo.UserInfo;
import com.wedo.auth.utils.JwtUtils;
import com.wedo.book.config.JwtProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("GET".equals(method)) {
            return true;
        }
        String token = request.getHeader("WD_TOKEN");
        if (StringUtils.isBlank(token)) {
            return false;
        }

        UserInfo userinfo = null;
        try {
            userinfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        if ("ADMIN".equals(userinfo.getRole())) {
            return true;
        }
        return false;
    }
}
